package com.zmkj.cn.comm.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
/**
 * 从 HttpServletRequest 获取IP地址
 * @author sunshine
 * @date 2022年7月4日
 */
public class IpUtils {
	
    private static final String UNKNOWN_STRING="unknown";

    private IpUtils() {
        throw new IllegalStateException("Utility class");
    }
    
    /**
     * 获取ip地址
     * @param request
     * @return String
     * @author sunshine
     * @date 2022年7月4日
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if(StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)){
        	ip = request.getHeader("X-Real-IP");  
        }
        if(StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)){
        	ip = request.getRemoteAddr();  
        }
        if(StringUtils.isEmpty(ip) || UNKNOWN_STRING.equalsIgnoreCase(ip)){
        	ip ="127.0.0.1";  
        }
        return ip.split(",")[0];
    }
}
